package com.diankangwo.factory.controller;

import com.diankangwo.common.annotation.SysLog;
import com.diankangwo.common.utils.PageUtils;
import com.diankangwo.common.utils.Query;
import com.diankangwo.common.utils.R;
import com.diankangwo.common.validator.ValidatorUtils;
import com.diankangwo.common.validator.group.AddGroup;
import com.diankangwo.common.validator.group.UpdateGroup;
import com.diankangwo.factory.annotation.LoginUser2;
import com.diankangwo.factory.dao.TdClassificationMapper;
import com.diankangwo.factory.dao.TdCommodityMapper;
import com.diankangwo.factory.dao.TdTypeMapper;
import com.diankangwo.factory.dto.TdFactoryDTO;
import com.diankangwo.factory.dto.TdFactoryDTO2;
import com.diankangwo.factory.entity.TdClassification;
import com.diankangwo.factory.entity.TdCommodity;
import com.diankangwo.factory.entity.TdFactory;
import com.diankangwo.factory.service.TdClassificationService;
import com.diankangwo.factory.service.TdFactoryService;
import com.diankangwo.sys.dao.SysUserDao;
import com.diankangwo.sys.entity.SysUserEntity;
import com.diankangwo.sys.service.SysUserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 厂家controller
 * Created by wuye on 2017/9/12.
 */
@RestController
@RequestMapping("/fac/fac")
public class TdFactoryController {

    @Autowired
    private SysUserDao sysUserDao;

    @Autowired
    private TdFactoryService tdFactoryService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private TdClassificationService tdClassificationService;

    @Autowired
    private TdTypeMapper tdTypeMapper;

    @Autowired
    private TdClassificationMapper tdClassificationMapper;

    @Autowired
    private TdCommodityMapper tdCommodityMapper;

    /**
     * 获取厂家列表
     */
    @ApiOperation(value = "获取厂家列表", notes = "")
    @ApiImplicitParam(name = "params", value = "查询条件", required = true, dataType = "Map<String,Object>")
    @RequestMapping("/list")
    @RequiresPermissions("fac:fac:list")
    public R list(@RequestParam Map<String, Object> params, @LoginUser2 SysUserEntity sysUserEntity) {
        Query query = new Query(params);
        List<TdFactoryDTO2> tdFactoryDTOList = new ArrayList<>();
        int total = 0;
        if (sysUserEntity.getTdFactoryid() == -1) {
            List<TdFactory> factoryList = tdFactoryService.queryList(query);
            //查询列表数据
            for (int i = 0; i < factoryList.size(); i++) {
                TdFactoryDTO2 tdFactoryDTO2 = new TdFactoryDTO2();
                tdFactoryDTO2.setTdFactory(factoryList.get(i));
                tdFactoryDTO2.setTdClassification(tdClassificationService.selectByPrimaryKey(factoryList.get(i).getClassificationid()));
                tdFactoryDTO2.setTdType(tdTypeMapper.selectByPrimaryKey(factoryList.get(i).getTypeid()));
                SysUserEntity userEntity = sysUserService.queryById(factoryList.get(i).getSysuserid());
                if (userEntity != null) {
                    userEntity.setPassword("");
                    userEntity.setRoleIdList(null);
                    userEntity.setMobile("");
                    userEntity.setSalt("");
                }
                tdFactoryDTO2.setUserEntity(userEntity);
                tdFactoryDTOList.add(tdFactoryDTO2);
            }
            total = tdFactoryService.queryTotal(query);
        } else if (sysUserEntity.getTdFactoryid() > 0) {
            TdFactory tdFactory = tdFactoryService.queryById(sysUserEntity.getTdFactoryid());
            TdFactoryDTO2 tdFactoryDTO2 = new TdFactoryDTO2();
            tdFactoryDTO2.setTdFactory(tdFactory);
            tdFactoryDTO2.setTdClassification(tdClassificationService.selectByPrimaryKey(tdFactory.getClassificationid()));
            tdFactoryDTO2.setTdType(tdTypeMapper.selectByPrimaryKey(tdFactory.getTypeid()));
            SysUserEntity userEntity = sysUserService.queryById(tdFactory.getSysuserid());
            userEntity.setPassword("");
            userEntity.setRoleIdList(null);
            userEntity.setMobile("");
            userEntity.setSalt("");
            tdFactoryDTO2.setUserEntity(userEntity);
            tdFactoryDTOList.add(tdFactoryDTO2);
        }
        PageUtils pageUtil = new PageUtils(tdFactoryDTOList, total, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    /**
     * 根据条件所有厂家列表
     */
    @ApiOperation(value = "根据条件所有厂家列表", notes = "")
    @ApiImplicitParam(name = "id", value = "查询条件", required = true, dataType = "Integer")
    @RequestMapping("/findById")
    @RequiresPermissions("fac:fac:findById")
    public R findById(@RequestParam Integer id) {
        //查询列表数据
        TdFactoryDTO2 tdFactoryDTO2 = new TdFactoryDTO2();
        TdFactory tdFactory = tdFactoryService.queryById(id);
        if (tdFactory != null) {
            tdFactoryDTO2.setTdFactory(tdFactory);
            tdFactoryDTO2.setTdClassification(tdClassificationService.selectByPrimaryKey(tdFactory.getClassificationid()));
            tdFactoryDTO2.setTdType(tdTypeMapper.selectByPrimaryKey(tdFactory.getTypeid()));
            tdFactoryDTO2.setUserEntity(sysUserService.queryById(tdFactory.getSysuserid()));
            return R.ok().put("tdFactory", tdFactoryDTO2);
        }
        return R.error("未查询到数据！");
    }

    /**
     * 保存厂家信息
     */

    @ApiOperation(value = "保存厂家", notes = "")
    @ApiImplicitParam(name = "tdFactoryDTO", value = "二级分类", required = true, dataType = "TdFactoryDTO")
    @SysLog("保存厂家")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @RequiresPermissions("fac:fac:save")
    public R save(@RequestBody TdFactoryDTO tdFactoryDTO) {
        ValidatorUtils.validateEntity(tdFactoryDTO.getTdFactory(), AddGroup.class);
        tdClassificationMapper.insert(tdFactoryDTO.getTdClassification());
        tdFactoryDTO.getTdFactory().setClassificationid(tdFactoryDTO.getTdClassification().getId());
        tdFactoryService.save(tdFactoryDTO.getTdFactory());
        SysUserEntity userEntity = sysUserService.queryById(tdFactoryDTO.getTdFactory().getSysuserid());
        userEntity.setTdFactoryid(tdFactoryDTO.getTdFactory().getId());
        ValidatorUtils.validateEntity(userEntity, UpdateGroup.class);
        sysUserService.update2(userEntity);
        return R.ok();
    }

    /**
     * 修改厂家
     */
    @ApiOperation(value = "修改厂家", notes = "")
    @ApiImplicitParam(name = "commodity", value = "修改厂家", required = true, dataType = "TdFactory")
    @SysLog("修改厂家")
    @RequestMapping("/update")
    @RequiresPermissions("fac:fac:update")
    public R update(@RequestBody TdFactoryDTO tdFactoryDTO) {
        ValidatorUtils.validateEntity(tdFactoryDTO, UpdateGroup.class);
        TdFactory tdFactory = tdFactoryService.queryById(tdFactoryDTO.getTdFactory().getId());
        TdFactory tdFactory1 = tdFactoryDTO.getTdFactory();
        TdClassification tdClassification = tdFactoryDTO.getTdClassification();
        tdClassificationMapper.updateByPrimaryKey(tdClassification);
        if (tdFactory.getSysuserid() != tdFactory1.getSysuserid()) {
            SysUserEntity sysUserEntity = sysUserService.queryById(tdFactory.getSysuserid());
            sysUserEntity.setTdFactoryid(0);
            sysUserService.update(sysUserEntity);
        }
        //更新厂家数据
        tdFactoryService.update(tdFactoryDTO.getTdFactory());
        return R.ok();
    }

    /**
     * 删除厂家
     */
    @ApiOperation(value = "删除厂家", notes = "")
    @ApiImplicitParam(name = "factoryId", value = "厂家ID", required = true, dataType = "Integer")
    @SysLog("删除厂家")
    @RequestMapping("/delete")
    @RequiresPermissions("fac:fac:delete")
    public R delete(Integer factoryId) {
        TdFactory tdFactory = tdFactoryService.queryById(factoryId);
        //查询该厂家下是否还存在商品，存在则无法删除
        List<TdCommodity> tdCommodityList = tdCommodityMapper.queryByFactoryId(factoryId);
        if (tdCommodityList.size() == 0) {
            //不存在商品，软删除
            tdFactory.setIsdelete(1);
            tdFactoryService.update(tdFactory);
            //更新厂家关联管理员的厂家状态
            List<SysUserEntity> sysUserEntityList = sysUserService.queryByFactoryId(factoryId);
            for (int i = 0; i < sysUserEntityList.size(); i++) {
                SysUserEntity sysUserEntity = sysUserEntityList.get(i);
                sysUserEntity.setTdFactoryid(0);
                sysUserService.update2(sysUserEntity);
            }
        } else {
            return R.error("厂家下面有商品，无法删除！");
        }
        return R.ok();
    }

    /**
     * 修改应结算比例
     */
    @ApiOperation(value = "修改应结算比例", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "factoryId", value = "厂家ID", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "updateByMoney", value = "应结算比例", required = true, dataType = "Integer")
    })
    @SysLog("修改应结算比例")
    @RequestMapping("/updateByMoney")
    @RequiresPermissions("fac:fac:updateByMoney")
    public R updateByMoney(Integer factoryId, float updateByMoney) {
        TdFactory tdFactory = tdFactoryService.queryById(factoryId);
        tdFactory.setBalanceproportion(updateByMoney);
        tdFactoryService.update(tdFactory);
        return R.ok();
    }

}
